package com.lxd;

import com.alibaba.fastjson.JSONObject;
import com.lxd.client.ClientHandler;
import com.lxd.entity.ChatMsg;
import com.lxd.entity.User;
import com.lxd.util.ProtostuffUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * @author liuxiaoding
 * 测试1对1发送消息，发送到client
 * @data 2019/7/2
 */
public class Client2 {
    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "7000"));
    static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));

    public static void main(String[] args) throws Exception {
        sendMessage("test2");
    }
    public static void sendMessage(String name) throws InterruptedException{
        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                            p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                            p.addLast(new ClientHandler());
                        }
                    });
            ChannelFuture future = b.connect(HOST, PORT).sync();
            //登录
            login(future,name);
            Scanner sca=new Scanner(System.in);
            while (true){
                String str=sca.nextLine();//输入的内容
                if (str.equals("exit"))
                    break;//如果是exit则退出
                sendMsg(future,name,str);//发消息
            }
            future.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully();
        }
    }

    public static void login(ChannelFuture future,String name){
        ChatMsg chatMsg = ChatMsg.builder().msgType(0).name(name).build();
        future.channel().writeAndFlush(JSONObject.toJSONString(chatMsg));
    }
    public static void sendMsg(ChannelFuture future,String name, String content){
        ChatMsg chatMsg= ChatMsg.builder().name(name).msgType(1).fromName(name).toName("test1").content(content).build();
        future.channel().writeAndFlush(JSONObject.toJSONString(chatMsg));
    }

}
